<template>
  <div class="form-container">
    <el-row :gutter="15">
      <el-col
        :xs="24"
        :sm="24"
        :md="12"
        :lg="8"
        :xl="8"
      >
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
          :status-icon="true"
        >
          <el-form-item
            v-if="user.level < 3"
            label="所属村"
            prop="villageWrap"
          >
            <el-cascader
              v-model="ruleForm.villageWrap"
              :options="villageCascader"
              :props="villageProp"
              placeholder="请选择党员所属村"
              clearable
              @change="change"
            />
          </el-form-item>
          <!-- 党员信息 -->
          <el-form-item
            label="所属组"
            prop="group"
          >
            <el-select
              v-model.number="ruleForm.group"
              placeholder="请选择所属组"
              clearable
            >
              <el-option
                v-for="item in groupAtt"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="姓名"
            prop="name"
          >
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入党员姓名"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="性别"
            prop="sex"
          >
            <el-select
              v-model.number="ruleForm.sex"
              placeholder="请选择性别"
              clearable
            >
              <el-option
                label="男"
                :value="0"
              />
              <el-option
                label="女"
                :value="1"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="民族"
            prop="nation"
          >
            <el-select
              v-model.number="ruleForm.nation"
              placeholder="请选择所属民族"
              clearable
            >
              <el-option
                v-for="(item, index) in nationAtt"
                :key="index"
                :label="item"
                :value="index + 1"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="手机号"
            prop="phone"
          >
            <el-input
              v-model="ruleForm.phone"
              placeholder="请输入党员手机号"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="身份证号"
            prop="identityNumber"
          >
            <el-input
              v-model="ruleForm.identityNumber"
              placeholder="请输入党员身份证号"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="家庭地址"
            prop="address"
          >
            <el-input
              v-model="ruleForm.address"
              placeholder="请输入党员家庭地址"
              clearable
            />
          </el-form-item>
          <!-- 党员信息 -->
          <el-form-item
            label="文化程度"
            prop="education"
          >
            <el-select
              v-model.number="ruleForm.education"
              placeholder="请选择党员文化程度"
              clearable
            >
              <el-option
                v-for="(item, index) in ['小学','初级中学','高级中学','专科','本科','硕士研究生','博士研究生']"
                :key="index"
                :label="item"
                :value="index"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="职务"
            prop="duties"
          >
            <el-input
              v-model="ruleForm.duties"
              type="textarea"
              placeholder="请输入党员所任职务"
              :rows="2"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="就职单位"
            prop="lnauguralAddress"
          >
            <el-input
              v-model="ruleForm.lnauguralAddress"
              type="textarea"
              placeholder="请输入党员就职单位"
              :rows="2"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="所属党组织"
            prop="partyOrganization"
          >
            <el-input
              v-model="ruleForm.partyOrganization"
              placeholder="请输入党员党组织"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="身份状态"
            prop="status"
          >
            <el-select
              v-model.number="ruleForm.status"
              placeholder="请选择党员身份状态"
              clearable
            >
              <el-option
                v-for="(item, index) in [
                  {
                    status: '积极分子',
                    value: 2
                  },
                  {
                    status: '发展对象',
                    value: 3
                  },
                  {
                    status: '发展对象',
                    value: 4
                  },
                  {
                    status: '正式党员',
                    value: 5
                  },
                ]"
                :key="index"
                :label="item.status"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.status >= 2"
            label="积极分子时间段"
            prop="periodOfActivists"
          >
            <el-date-picker
              v-model="ruleForm.periodOfActivists"
              align="right"
              placeholder="选择党员积极分子时间段"
              value-format="yyyy-MM"
              type="month"
              :picker-options="pickerOptions2"
              clearable
            />
          </el-form-item>
          <el-form-item
            v-if="ruleForm.status >= 3"
            label="发展对象时间段"
            prop="periodOfDevelopmentObject"
          >
            <el-date-picker
              v-model="ruleForm.periodOfDevelopmentObject"
              align="right"
              placeholder="选择党员发展对象时间段"
              value-format="yyyy-MM"
              type="month"
              :picker-options="pickerOptions2"
              clearable
            />
          </el-form-item>
          <el-form-item
            v-if="ruleForm.status >= 4"
            label="预备党员时间段"
            prop="periodOfProbationaryMember"
          >
            <el-date-picker
              v-model="ruleForm.periodOfProbationaryMember"
              align="right"
              placeholder="选择党员预备党员时间段"
              value-format="yyyy-MM"
              type="month"
              :picker-options="pickerOptions2"
              clearable
            />
          </el-form-item>
          <el-form-item
            v-if="ruleForm.status >= 5"
            label="正式党员时间段"
            prop="periodOfPartyMember"
          >
            <el-date-picker
              v-model="ruleForm.periodOfPartyMember"
              align="right"
              placeholder="选择党员正式党员时间段"
              value-format="yyyy-MM"
              type="month"
              :picker-options="pickerOptions2"
              clearable
            />
          </el-form-item>

          <el-form-item
            label="相关图片"
            prop="imgAtt"
          >
            <el-upload
              :action="uploadUrl"
              :headers="getAuthHeaders()"
              list-type="picture-card"
              :file-list="ruleForm.image"
              :on-success="handleSuccess"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :limit="1"
              accept=".Webp,.baiBMP,.PCX,.TIF,.GIF,.JPEG,.JPG,.TGA,.EXIF,.FPX,.SVG,.PSD,.CDR,.PCD,.DXF,.UFO,.EPS,.AI,.PNG,.HDRI,.RAW,.WMF,.FLIC,.EMF,.ICO,"
            >
              <i class="el-icon-plus" />
            </el-upload>
            <el-dialog
              :visible.sync="dialogVisible"
              size="tiny"
            >
              <img
                width="100%"
                :src="dialogImageUrl"
                alt
              >
            </el-dialog>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
            >
              {{ !id ? "立即创建" : "保存编辑" }}
            </el-button>
            <el-button @click="resetForm('ruleForm')">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
//手动添加
import { mapGetters } from "vuex";
export default {
  name: "Form",
  props: {
    id: {},
  },
  data() {
    var imageValidator = (rule, value, callback) => {
      if (this.imgAtt.length > 0) {
        callback();
      } else {
        callback(new Error('请上传图片'));
      }
    };
    return {
      ruleForm: {
        // villagerInfo: {
          name: "",
          //性别
          sex: 0,  
          //民族
          nation: 1,
          //手机号
          phone: "",
          //身份证号
          identityNumber: "",
          //籍贯
          address: "",
        // },
        group: "",
        villageWrap: [],
        village: "",
        villager: "",
        duties: "",
        education: null,
        lnauguralAddress: "",
        status: 2,
        periodOfActivists: "",
        periodOfDevelopmentObject: "",
        periodOfProbationaryMember: "",
        periodOfPartyMember: "",
        partyOrganization: "",
      },
      rules: {
        
        villageWrap: [
          { required: true, message: "请选择党员所属村", trigger: "change" },
        ],
        villager: [
          {
            required: true,
            message: "请选择党员党员身份",
            trigger: "change",
          },
        ],
        duties: [
          { required: false, message: "请输入党员职务", trigger: "blur" },
        ],
         education: [
          { required: false, message: "请选择党员教育水平", trigger: "change" },
        ],
         lnauguralAddress: [
          { required: false, message: "请输入党员任职地点", trigger: "blur" },
        ],
        status: [
          { required: true, message: "请选择党员身份状态", trigger: "change" },
        ],
        periodOfActivists: [{ required: true, message: "请选择党员积极分子时间段", trigger: "change" }],
        periodOfDevelopmentObject: [{ required: true, message: "选择党员发展对象时间段", trigger: "change" }],
        periodOfProbationaryMember: [{ required: true, message: "选择党员预备党员时间段", trigger: "change" }],
        periodOfPartyMember: [{ required: true, message: "选择党员正式党员时间段", trigger: "change" }],

        'name': [
          { required: true, message: "请输入党员姓名", trigger: "blur" }
        ],
        'sex': [
          { required: true, message: "请选择性别", trigger: "change" }
        ],
        'nation': [
          { required: true, message: "请选择所属民族", trigger: "change" }
        ],
        'phone': [
          {
                required: false, message: "请输入党员手机号", trigger: "blur"
          }
        ],
        'identityNumber': [
          {
                required: false, message: "请输入党员身份证号", trigger: "blur"
          }
        ],
        'address': [
          {
                required: false, message: "请输入党员家庭地址", trigger: "blur"
          }
        ],
        partyOrganization: [
          { required: true, message: "请输入党员所属党组织", trigger: "blur" },
        ],
        imgAtt: [
          { required: true, validator: imageValidator,  trigger: "change" },
        ],
      },
      dialogImageUrl: "",
      dialogVisible: false,
      imgAtt: [],
      groupAtt: [],
      createForm: {},
      villageCascader: [],
      villageProp: {
        value: "id",
        label: "name",
      },
      pickerOptions2: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      nationAtt: [
        "汉族",
        "蒙古族",
        "回族",
        "藏族",
        "维吾尔族",
        "苗族",
        "彝族",
        "壮族",
        "布依族",
        "朝鲜族",
        "满族",
        "侗族",
        "瑶族",
        "白族",
        "土家族",
        "哈尼族",
        "哈萨克族",
        "傣族",
        "黎族",
        "傈僳族",
        "佤族",
        "畲族",
        "高山族",
        "拉祜族",
        "水族",
        "东乡族",
        "纳西族",
        "景颇族",
        "柯尔克孜族",
        "土族",
        "达斡尔族",
        "仫佬族",
        "羌族",
        "布朗族",
        "撒拉族",
        "毛南族",
        "仡佬族",
        "锡伯族",
        "阿昌族",
        "普米族",
        "塔吉克族",
        "怒族",
        "乌孜别克族",
        "俄罗斯族",
        "鄂温克族",
        "德昂族",
        "保安族",
        "裕固族",
        "京族",
        "塔塔尔族",
        "独龙族",
        "鄂伦春族",
        "赫哲族",
        "门巴族",
        "珞巴族",
        "基诺族",
      ],
    };
  },
  computed: {
    ...mapGetters({
      user: "user/info",
    }),
  },
  watch: {
  },
  async created() {
    this.init();
    this.id && this.fetchData(this.id);
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid && this.id) {
          // alert("submit!");
          this.edit()
        } else if(valid && !this.id) {
          // return false;
          this.create();
        } else {
          return false
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(res, file, fileList) {
      let att = [];
      fileList.forEach((file) =>
        att.push(file.response ? file.response : file)
      );
      this.imgAtt = att;
      console.log(this.imgAtt)
    },
    handleRemove(file, fileList) {
      let att = [];
      fileList.forEach((file) =>
        att.push(file.response ? file.response : file)
      );
      this.imgAtt = att;
      console.log(this.imgAtt)
    },
    resPip() {
      this.createForm = JSON.parse(JSON.stringify(this.ruleForm));
      this.createForm.image = this.imgAtt;
      this.clearNullField(this.createForm, 'group')
    },
    async create() {
      this.resPip();
      const res = await this.$http.post(`/party-member`, this.createForm);
      if (res.status == 201) {
        this.$baseMessage("新增成功", "success");
        this.$router.push({ name: "PartyMember" });
      } else {
        this.$baseMessage("新增失败", "error");
      }
    },
    async edit() {
      this.resPip();
      const res = await this.$http.put(
        `/party-member/${this.id}`,
        this.createForm
      );
      if (res.status == 200) {
        this.$baseMessage("修改成功", "success");
        this.$router.push({ name: "PartyMember" });
      } else {
        this.$baseMessage("修改失败", "error");
      }
    },
    async fetchData(id) {
      const res = await this.$http.get(`/party-member/${id}?join=village&join=group`);

      res.data.image = this.imgAtt = res.data.image || []

      //处理关联
      // res.data.villager = res.data.villager.id;

      const town = await this.$http.get(`village/${res.data.village.id}?join=town`);

      this.villagerAtt = town.data.villager;
      const area = await this.$http.get(`town/${town.data.town.id}?join=area`);
      res.data.villageWrap = [
        area.data.area.id,
        town.data.town.id,
        res.data.village.id,
      ];

      this.ruleForm = Object.assign({}, res.data);

      this.change([area.data.area.id, town.data.town.id, res.data.village.id]);

      this.ruleForm.group = res.data.group.id
    },
    async init() {
      const res = await this.$http.get(`area?join=town&join=town.village`);
      res.data.forEach(area => {
        area.children = area.town
        area.town.forEach(town => {
          town.children = town.village
        })
      })
      this.villageCascader = res.data;
      this.setSelectItem()
    },
    async change(val) {
      this.ruleForm.village = val[val.length - 1];
      this.ruleForm.group = "";
      const res = await this.$http.get(`village/${this.ruleForm.village}?join=group`);
      this.groupAtt = res.data.group
    },
    setSelectItem() {
      if(this.user.level < 1) {
      } else if (this.user.level == 1) {
        //区级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                town.disabled = true
              });
            }
          }
        });
      } else if (this.user.level == 2) {
        //镇级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
             if (area.town.length > 0) {
              area.town.forEach((town) => {
                if(town.id == this.user.town.id) {
                  town.disabled = false
                } else {
                  town.disabled = true
                }
              });
            }
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                  town.disabled = true
              });
            }
          }
        });
      } else if (this.user.level == 3) {
          //村级
        this.change([this.user.village.id])
      } 
    },
  },
};
</script>
